/**
 * 
 */
package com.humanmonth.rea.pic;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.humanmonth.framework.web.servlet.Action;
import com.humanmonth.framework.web.servlet.AutoMapperServlet;
import com.humanmonth.framework.web.servlet.ServletUtil;

/**
 * @author 林子龙
 * 
 */
@SuppressWarnings("serial")
public class PictureServlet extends AutoMapperServlet {
private Logger log=Logger.getLogger(this.getClass().getName());
	/**
	 * 测试
	 */
	@Action("sayHi")
	public void sayHi(HttpServletRequest req, HttpServletResponse res) throws IOException {
		ServletUtil.outTips(res, "hi", null);
	}

	/**
	 * 保存图片
	 */
	@Action("savePic")
	public void savePic(HttpServletRequest req, HttpServletResponse res) throws IOException {
String name= ServletUtil
.getStringParameterWithTrim(req, "name");
if(name==null){
	name="签名.jpg";
}
		Picture pic = new Picture(ServletUtil.getStringParameterWithTrim(req, "module"),name, new Blob(IOUtils.toByteArray(req.getInputStream())));
		new PictureService().savePic(pic);
		log.info("保存的文件大小："+pic.getContent().getBytes().length);
		ServletUtil.outView(res, pic.getId());
	}

	/**
	 * 查找所有图片
	 */
	@Action("queryAllPic")
	public void queryAllPic(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String result = "";
		for (Picture pic : new PictureService().queryAllPicture()) {
			if (pic.getContent() == null) {
				continue;
			}
			result += new String(pic.getContent().getBytes(), "utf-8") + ":";
		}
		ServletUtil.outView(res, result);
	}

	/**
	 * 以ID获取图片
	 */
	@Action("queryPicById")
	public void queryPicById(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String id = ServletUtil.getStringParameterWithTrim(req, "pid");
		log.info("开始下载文件,ID为:"+id);
		Picture pic = new PictureService().queryPicById(Long.valueOf(id));
		log.info("下载的文件大小："+pic.getContent().getBytes().length);
		ServletUtil.downloadToClient(res, pic.getContent().getBytes(), pic.getName());
	}
}
